"""
审计服务
========

处理审计日志记录
"""

import json
from datetime import datetime, timezone
from typing import Optional, Dict, Any
from redfire_framework.core.database import create_database_manager


class AuditService:
    """审计服务类"""
    
    def __init__(self, config: Dict[str, Any]):
        self.database_manager = create_database_manager(config.get("database", {}))
        self.config = config
        self.enabled = config.get("enabled", True)
    
    async def log_user_action(
        self, 
        user_id: str, 
        action: str, 
        details: Optional[Dict[str, Any]] = None
    ):
        """记录用户操作日志"""
        if not self.enabled:
            return
        
        try:
            # 这里可以实现实际的日志记录逻辑
            # 比如写入数据库、发送到日志系统等
            log_entry = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "user_id": user_id,
                "action": action,
                "details": details or {},
                "category": "user_action"
            }
            
            # 输出到日志
            import logging
            logger = logging.getLogger(__name__)
            logger.info(f"User Action: {json.dumps(log_entry)}")
            
        except Exception as e:
            # 审计日志失败不应该影响主流程
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to log user action: {e}")
    
    async def log_security_event(
        self, 
        event_type: str, 
        details: Optional[Dict[str, Any]] = None,
        user_id: Optional[str] = None
    ):
        """记录安全事件日志"""
        if not self.enabled:
            return
        
        try:
            log_entry = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "event_type": event_type,
                "user_id": user_id,
                "details": details or {},
                "category": "security_event"
            }
            
            import logging
            logger = logging.getLogger(__name__)
            logger.warning(f"Security Event: {json.dumps(log_entry)}")
            
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to log security event: {e}")
    
    async def log_error(
        self, 
        error_type: str, 
        error_message: str,
        details: Optional[Dict[str, Any]] = None,
        user_id: Optional[str] = None
    ):
        """记录错误日志"""
        if not self.enabled:
            return
        
        try:
            log_entry = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "error_type": error_type,
                "error_message": error_message,
                "user_id": user_id,
                "details": details or {},
                "category": "error"
            }
            
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Error Log: {json.dumps(log_entry)}")
            
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to log error: {e}")
